//
//  HTTPClient.swift
//  微博个人swift
//
//  Created by 李灏 on 16/2/24.
//  Copyright © 2016年 lh. All rights reserved.
//

import UIKit
import AFNetworking

//网络请求方式
//枚举在swift中更加强大 可以枚举任何类型
enum HTTPMethod: String {
    case GET = "GET"
    case POST = "POST"
}
class HTTPClient: AFHTTPSessionManager {
    
    //定义反转域名
    let domain = "com.baidu.data.error"
    
    //单例
    static let sharedClient:HTTPClient = {
        let urlString = "https://api.weibo.com/"
        let url = NSURL(string: urlString)
        let tools = HTTPClient(baseURL: url)
        //设置支持解析的数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //网络请求方法的封装  GET + POST
    func requestJSONDict(method: HTTPMethod,urlString: String,parameters: [String : AnyObject]?,finished: (dict: [String : AnyObject]?,error: NSError?) -> () ) {
        if method == .GET {
            //get请求
            GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                print(result)
                guard let dict = result as? [String : AnyObject] else {
                    //获取的数据不能够转换为字典类型数据
                    //执行失败的回调
                    //自定义错误信息
                    //domain: 域名的反转信息 cn.itcast
                    //自定义错误码 一般为 负数  或者 大于10000
                    let myError = NSError(domain: self.domain, code: 10000, userInfo: [NSLocalizedDescriptionKey : "数据结构出错"])
                    finished(dict: nil, error: myError)
                    return
                    
                }
                
                
                //执行成功的回调
                finished(dict: dict, error: nil)
                }, failure: { (_, error) -> Void in
                    finished(dict: nil, error: error)
                    print(error)
            })
        } else {
            //POST请求
            POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                guard let dict = result as? [String : AnyObject] else {
                    //获取的数据不能够转换为字典类型数据
                    //执行失败的回调
                    //自定义错误信息
                    //domain: 域名的反转信息 cn.itcast
                    //自定义错误码 一般为 负数  或者 大于10000
                    let myError = NSError(domain: self.domain, code: 10000, userInfo: [NSLocalizedDescriptionKey : "数据结构出错"])
                    finished(dict: nil, error: myError)
                    return
                    
                }
                
                //执行成功的回调
                finished(dict: dict, error: nil)
                }, failure: { (_, error) -> Void in
                    finished(dict: nil, error: error)
                    print(error)
            })
        }
    }
}
